
const emptyBox = document.querySelector('.empty')
const cartListBox = document.querySelector('.cart')

const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')

!id ? (window.location.href = './login.html') : getCartList()

async function getCartList() {  const res = await pAjax({
    url: 'http://localhost:8888/cart/list',
    data: { id },
    headers: { authorization: token },
    dataType: 'json',
  })

  if (res.code === 401) {
    window.location.href = './login.html'
    return
  }
  bindHtml(res)
}



function bindHtml(res) {
  if (!res.cart.length) {
    emptyBox.classList.add('active')
    cartListBox.classList.remove('active')
    return
  }

  let totalNum = 0,
    totalPrice = 0,
    totalSelect = 0
  res.cart.forEach(item => {
    if (item.is_select) {
      totalNum += item.cart_number
      totalPrice += item.cart_number * item.current_price
      totalSelect++
    }
  })

  let str = `
    <div class="top">
      全选 <input class="select_all" type="checkbox" ${totalSelect === res.cart.length ? 'checked' : ''}>
    </div>
    <ul class="cart_list">
  `

  res.cart.forEach(item => {
    str += `
      <li>
        <div class="select">
          <input data-id="${item.goods_id}" class="select_item" type="checkbox" ${item.is_select ? 'checked' : ''}>
        </div>
        <div class="show">
          <img src="${item.img_small_logo}" alt="">
        </div>
        <div class="title">${item.title}</div>
        <div class="price">￥${item.current_price}</div>
        <div class="number">
          <button class="sub_btn" data-id="${item.goods_id}" data-num="${item.cart_number}">-</button>
          <input type="text" value="${item.cart_number}">
          <button data-num="${item.cart_number}" data-id="${item.goods_id}" data-max="${item.goods_number}" class="add_btn">+</button>
        </div>
        <div class="subPrice">￥${(item.current_price * item.cart_number).toFixed(2)}</div>
        <div class="delete">
          <button data-id="${item.goods_id}" class="delete_btn">删除</button>
        </div>
      </li>
    `
  })

  str += `
    </ul>
    <div class="bottom">
      <p class="totalNum">
        总计 : ${totalNum} 件商品
      </p>
      <div class="btns">
        <button class="clear">清空购物车</button>
        <button class="delAll${totalSelect === 0 ? ' disable' : ''}">删除所有已选中</button>
        <button class="pay${totalSelect === 0 ? ' disable' : ''}">去支付</button>
      </div>
      <p class="totalPrice">
        总计 : ￥ ${totalPrice.toFixed(2)}
      </p>
    </div>
  `

  cartListBox.innerHTML = str
  cartListBox.classList.add('active')
  emptyBox.classList.remove('active')
}

cartListBox.addEventListener('click', async e => {
  if (e.target.className === 'select_item') {
    const goodsId = e.target.dataset.id

    const res = await pAjax({
      url: 'http://localhost:8888/cart/select',
      method: 'POST',
      data: { id, goodsId },
      headers: { authorization: token },
      dataType: 'json',
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'delete_btn') {
    const goodsId = e.target.dataset.id
    const res = await pAjax({
      url: 'http://localhost:8888/cart/remove',
      data: { id, goodsId },
      headers: { authorization: token },
      dataType: 'json',
    })
    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'add_btn') {
    const goodsId = e.target.dataset.id
    const num = e.target.dataset.num - 0
    const maxNum = e.target.dataset.max - 0

    if (num >= maxNum) return alert('库存已经不够了')

    const res = await pAjax({
      url: 'http://localhost:8888/cart/number',
      method: 'POST',
      data: { id, goodsId, number: num + 1 },
      headers: { authorization: token },
      dataType: 'json',
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'sub_btn') {
    const goodsId = e.target.dataset.id
    const num = e.target.dataset.num - 0

    if (num <= 1) return alert('别再少了, 再少没有了')

    const res = await pAjax({
      url: 'http://localhost:8888/cart/number',
      method: 'POST',
      data: { id, goodsId, number: num - 1 },
      headers: { authorization: token },
      dataType: 'json',
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'select_all') {
    const type = e.target.checked ? 1 : 0

    const res = await pAjax({
      url: 'http://localhost:8888/cart/select/all',
      method: 'POST',
      data: { id, type },
      dataType: 'json',
      headers: { authorization: token },
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'delAll') {
    const res = await pAjax({
      url: 'http://localhost:8888/cart/remove/select',
      data: { id },
      dataType: 'json',
      headers: { authorization: token },
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'clear') {
    const res = await pAjax({
      url: 'http://localhost:8888/cart/clear',
      data: { id },
      headers: { authorization: token },
      dataType: 'json',
    })

    if (res.code === 1) getCartList()
  }

  if (e.target.className === 'pay') {
    const res = await pAjax({
      url: 'http://localhost:8888/cart/pay',
      method: 'POST',
      data: { id },
      headers: { authorization: token },
      dataType: 'json',
    })

    console.log(res)
  }
})
